/* eslint-disable no-plusplus */
/* eslint-disable no-await-in-loop */
const { Controller } = require('egg');
const { error } = require('../utils/service');

class ProjectController extends Controller {
  async createProject() {
    const { ctx } = this;
    const { name, description } = ctx.request.body;
    await this.app.mysql.insert('project', { name, description, creator: ctx.session.username });
    const projectId = await this.app.mysql.query(`select max(id) as id from project`);
    await this.app.mysql.insert('userProject', {
      account: ctx.session.account,
      projectId: projectId[0].id,
    });
  }

  async getProjectList() {
    const { ctx } = this;

    const { keyword = '', pageSize = 20 } = ctx.request.body;
    let { pageNo = 1 } = ctx.request.body;
    const getProjectList = async () =>
      this.app.mysql.query(
        `select SQL_CALC_FOUND_ROWS  id,name,description,creator,star
         from userProject join project on  userProject.projectId= project.id  where account=? 
         and (name like '%${keyword}%' or description like '%${keyword}%')  limit ?,?`,
        [ctx.session.account, (pageNo - 1) * pageSize, pageSize]
      );

    let projectList = await getProjectList();
    if (projectList.length === 0) {
      pageNo = 1;
      projectList = await getProjectList();
    }

    const total = (await this.app.mysql.query(`select FOUND_ROWS()`))[0]['FOUND_ROWS()'];

    const projectListLength = projectList.length;

    for (let i = 0; i < projectListLength; i++) {
      const tempArray = await this.app.mysql.select('userProject', {
        where: {
          projectId: projectList[i].id,
        },
      });

      const members = await tempArray.reduce(async (pre, item) => {
        (await pre).push((await this.app.mysql.get('user', { account: item.account })).username);
        return pre;
      }, []);
      projectList[i].members = members;
    }
    ctx.body.total = total;
    ctx.body.pageNo = pageNo;
    ctx.body.pageSize = pageSize;
    ctx.body.content = projectList;
  }

  async searchProjectList() {
    const { ctx } = this;

    const { keyword } = ctx.request.body;
    let projectList = [];
    if (keyword) {
      projectList = await this.app.mysql.query(
        `select id,name,description
           from userProject join project on  userProject.projectId= project.id  where account=? 
           and (name like '%${keyword}%' or description like '%${keyword}%')`,
        [ctx.session.account]
      );
    }
    ctx.body.content = projectList;
  }

  async getProjectDetail() {
    const { ctx } = this;

    const { id } = ctx.request.body;
    const projectDetail = (
      await this.app.mysql.query(
        `select id,name,description,star,funcMergedCount,moduleMergedCount,func,module from project join userProject 
		on project.id = userProject.projectId where id = ?`,
        [id]
      )
    )[0];
    projectDetail.funcLength = (projectDetail.func && JSON.parse(projectDetail.func).length) || 0;
    projectDetail.moduleLength =
      (projectDetail.module && JSON.parse(projectDetail.module).length) || 0;
    delete projectDetail.func;
    delete projectDetail.module;
    const { projectCount } = (
      await this.app.mysql.query(`select count(*) as projectCount from project`)
    )[0];
    const { lessProjectCount } = (
      await this.app.mysql.query(
        `select count(*) as lessProjectCount from project where moduleMergedCount < ?`,
        [projectDetail.moduleMergedCount]
      )
    )[0];

    projectDetail.moduleMergedCountPerscent = lessProjectCount / projectCount;
    ctx.body.content = projectDetail;
  }

  async deleteProject() {
    const { ctx } = this;
    const { id } = ctx.request.body;
    await this.app.mysql.delete('project', { id });
  }

  async updateProject() {
    const { ctx } = this;
    const { id, name, description } = ctx.request.body;
    await this.app.mysql.update('project', { id, name, description });
  }

  async starProject() {
    const { ctx } = this;
    const { id, star } = ctx.request.body;
    await this.app.mysql.update('userProject', { star: !star }, { where: { projectId: id } });
  }

  async getStaredProjectList() {
    const { ctx } = this;
    const staredList = await this.app.mysql.query(
      `select id,name,description,star
			 from userProject join project on  userProject.projectId= project.id
			 where account=? and star = 1 `,
      [ctx.session.account]
    );
    ctx.body.content = staredList;
  }

  async getMemberList() {
    const { ctx } = this;
    const { id } = ctx.request.body;
    const memberList = await this.app.mysql.query(
      `select username,joinDate,userProject.account from userProject join user on  
		userProject.account=user.account where projectId = ?`,
      [id]
    );
    ctx.body.content = memberList;
  }

  async deleteMember() {
    const { ctx } = this;
    const { account, id } = ctx.request.body;
    await this.app.mysql.delete('userProject', { account, projectId: id });
  }

  async addMember() {
    const { ctx } = this;
    const { userList, id } = ctx.request.body;
    const len = userList.length;

    for (let i = 0; i < len; i++) {
      const result = await this.app.mysql.get('userProject', {
        account: userList[i],
        projectId: id,
      });
      if (result) {
        throw error(`用户${userList[i]}已加入该项目！`, 400);
      }
    }

    for (let i = 0; i < len; i++) {
      await this.app.mysql.insert('userProject', { account: userList[i], projectId: id });
    }
  }
}

module.exports = ProjectController;
